package cn.web.tunnelrobot.websocket;

import cn.web.tunnelrobot.StartService;
import cn.web.tunnelrobot.dao.WarningRecordDao;
import cn.web.tunnelrobot.dto.Warning;
import cn.web.tunnelrobot.dto.WarningRecordDTO;
import cn.web.tunnelrobot.util.Constants;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.java_websocket.WebSocket;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Date;

/**
 * @description:
 * @author: LiChuang
 * @createDate: 2021-6-22
 * @version: 1.0
 */
@Slf4j
@Component
public class MyWebSocketClient {
    private static final Logger logger = LoggerFactory.getLogger(MyWebSocketClient.class);

    public static void createClient() {
        try {
            URI uri = new URI("ws://449z7031f9.qicp.vip:44387/");
            //URI uri = new URI("ws://t40541z985.qicp.vip/");
            //URI uri = new URI("ws://tunnelrobot.natapp1.cc/");
//            URI uri = new URI("ws://192.168.0.180:9085/");
            WebSocketClient client = new WebSocketClient(uri) {
                @Override
                public void onOpen(ServerHandshake serverHandshake) {
                    logger.info("安全帽信息检测服务连接成功...");
                }

                @Override
                public void onMessage(String msg) {
                    logger.info("返回的数据：" + msg);

                    //对消息做业务处理
                    //JSON字符串转换成JSON对象
                    JSONObject jsonObject = JSONObject.parseObject(msg);
                    if(jsonObject.getString("MessageType").equals("Login") && jsonObject.getString("Return").equals("False")){
                        try{
                            Thread.sleep(2000);
                        }catch (Exception e){}
                    }
                    if(jsonObject.getString("MessageType").equals("AlarmEvent")){
                       String RuleNameStr = jsonObject.getString("RuleNameStr");
                       String ThumbnailPath = jsonObject.getString("ThumbnailPath");
                       //logger.info("报警信息：" + RuleNameStr+","+ThumbnailPath);
                       //添加警告信息
                       WarningRecordDao warningRecordDao = (WarningRecordDao)ApplicationHelper.getBean("warningRecordDao");
                       WarningRecordDTO warningRecordDTO = new WarningRecordDTO();
                       warningRecordDTO.setWrLevel("Ⅰ");
                       warningRecordDTO.setWrDescribe(RuleNameStr);
                       warningRecordDTO.setWrWarningTime(new Date());
                       warningRecordDTO.setWrImageUrl(ThumbnailPath);
                       warningRecordDao.addWarningRecordInfo(warningRecordDTO);
                       Warning warning = new Warning();
                       warning.setId(warningRecordDTO.getWrId());
                       warning.setCode(2001);
                       warning.setLevel("Ⅰ");
                       warning.setMsg(RuleNameStr);
                       warning.setUrl(ThumbnailPath);
                       Constants.warningList.add(warning);
                       StartService.timer();
                   }
                }

                @Override
                public void onClose(int i, String s, boolean b) {
                    logger.info("安全帽信息检测服务连接关闭");
                    try{
                        Thread.sleep(500);
                    }catch (Exception e){}
                    createClient();//连接关闭后重新开启
                }

                @Override
                public void onError(Exception e) {
                    e.printStackTrace();
                    logger.error("发生错误，关闭");
                    try{
                        Thread.sleep(500);
                    }catch (Exception es){}
                    createClient();//连接关闭后重新开启
                }
            };
            //建立连接
            client.connect();
            while (!client.getReadyState().equals(WebSocket.READYSTATE.OPEN)) {
                //logger.info("连接中...");
            }
            String dial = "{\"MessageType\":\"Login\",\"UserName\":\"" + "test" + "\",\"Password\":\"" + "test123" + "\"}";
            client.send(dial);
        } catch (URISyntaxException e) {
            logger.info(e.getMessage());
        }
    }
}
